package com.bpf.base.controller.system;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bpf.base.util.AjaxUtils;
import com.bpf.base.util.ExcelUitl;
import com.bpf.base.util.MapUtil;
import com.bpf.base.common.Constants;
import com.bpf.base.controller.BaseController;
import com.bpf.base.model.system.TSysUser;
import com.bpf.base.bean.system.TSysUserForm;
import com.bpf.base.service.system.TSysUserService;

/**
 * @date 2016-07-18 04:13:37
 */
@Controller
@RequestMapping("/system/user")
public class TSysUserController extends BaseController{
	private Logger logger = LoggerFactory.getLogger(TSysUserController.class);

    @Resource
	private TSysUserService tSysUserService;
    
	
    @RequestMapping(value = { "/init", "" })
	public String init() {
		return "system/user";
	}

    /**
	 * 根据条件查询
	 * @param params
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping("/getTSysUserList")
	@ResponseBody
	public Map<String, Object> getTSysUserList(HttpServletRequest request, TSysUserForm form,String jsonpCallback){
		Integer pageNum = Integer.parseInt(null == request.getParameter("page") ? 1 + "" : request.getParameter("page").toString());
		Integer pageSize = Integer.parseInt(null == request.getParameter("rows") ? 10 + "" : request.getParameter("rows").toString());
		Map<String, Object> params = new HashMap<String, Object>();
		params = MapUtil.toMap(form);
		params.put("offset", (pageNum-1)*pageSize);
		params.put("limit", pageSize);
		return tSysUserService.getTSysUserList(params);
	}    

  	@RequestMapping("/addTSysUser")
	@ResponseBody
	public Map<String, Object> addTSysUser(HttpServletRequest request, TSysUser form,String jsonpCallback) throws UnsupportedEncodingException{
		Map<String, Object> params = new HashMap<String, Object>();
		// 参数检查
		params = MapUtil.toMap(form);
		// 调用service
		tSysUserService.addTSysUser(params);
		return AjaxUtils.reponseToJson("添加", true);
	}
	
	/**
	 * 更新
	 * @param params
	 * @return
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws JSONException
	 */
	@RequestMapping("/updateTSysUser")
	@ResponseBody
	public Map<String, Object> updateTSysUser( TSysUser form,String jsonpCallback) throws InstantiationException, IllegalAccessException{
		// 参数检查
		TSysUser tSysUser = MapUtil.toObject(TSysUser.class, MapUtil.toMap(form));
		// 调用service
		tSysUserService.updateTSysUser(tSysUser);
		return AjaxUtils.reponseToJson("修改", true);
	}
	
	/**
	 * 删除
	 * @param params
	 * @return
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws JSONException
	 */
	@RequestMapping("/deleteTSysUser")
	@ResponseBody
	public Map<String, Object> deleteTSysUser(HttpServletRequest request,String jsonpCallback) throws InstantiationException, IllegalAccessException{
		String[] idArray=request.getParameterValues("idArray[]");
		// 调用service
		if(tSysUserService.delTSysUserBat(idArray) > 0){
			return AjaxUtils.reponseToJson("删除", true);
		}else{
			return AjaxUtils.reponseToJson("删除", false);
		}
	}
	
	@RequestMapping("/exporttSysUser")
	public void exportTSysUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		OutputStream out = response.getOutputStream();
		String title = "业主信息";
		String[] headers = { "住户编号", "业主姓名", "房产证", "土地证", "性别", "身份证", "联系电话" };
		String[] columns = { "id", "name", "housePropertyCert", "landCert", "gender", "idNo", "mobile" };
		List<TSysUser> houseList = tSysUserService.getAllTSysUser(null);
		ExcelUitl<TSysUser> excelUtil = new ExcelUitl<TSysUser>();
		String pattern = "yyyy-MM-dd HH:mm:dd";
		response.setHeader("Content-Disposition", "attachment;filename=" + new String((title + ".xls").getBytes(), "iso-8859-1"));
		excelUtil.exportoExcel(title, headers, columns, houseList, out, pattern);
	}
	
	@RequestMapping("/getTSysUserAllList")
	@ResponseBody
	public List<TSysUser> getTSysUserAllList(HttpServletRequest request, TSysUserForm form,String jsonpCallback){
		Map<String, Object> params = new HashMap<String, Object>();
		params = MapUtil.toMap(form);
		return tSysUserService.getAllTSysUser(params);
	}
	
	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(HttpServletRequest request,TSysUserForm userSearch) {
		Integer pageNum = Integer.parseInt(null == request.getParameter("page") ? 1 + "" : request.getParameter("page").toString());
		Integer pageSize = Integer.parseInt(null == request.getParameter("rows") ? 10 + "" : request.getParameter("rows").toString());
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put(Constants.Page.OFFSET, (pageNum - 1) * pageSize);
		conditions.put(Constants.Page.LIMIT, pageSize);
		conditions.put(Constants.Condition.ORDERBY_CLAUSE, "USER_ID DESC");
		return tSysUserService.getTSysUserList(conditions);
	}
	
	//判断用户名是否存在
	@ResponseBody
	@RequestMapping(value = "/checkUsername")
	public Boolean ckeckUsername(String username) {
		TSysUserForm form=new TSysUserForm();
		form.setUsername(username);
		return tSysUserService.getAllTSysUser(MapUtil.toMap(form)).isEmpty();
	}
	
	
	@RequestMapping(value = "/save")
	@ResponseBody
	public Map<String, Object> save(TSysUser user) {
		//user.setPassword(ConfigUtil.getConfig("init.password"));
		tSysUserService.addTSysUser(MapUtil.toMap(user));
		return AjaxUtils.reponseToJson(Constants.Action.SAVE, true);
	}

	@ResponseBody
	@RequestMapping(value = "/edit/{id}")
	public TSysUser edit(@PathVariable(value = "id") Integer id) {
		TSysUserForm form=new TSysUserForm();
		form.setUserId(id);
		return tSysUserService.getAllTSysUser(MapUtil.toMap(form)).get(0);
	}

	@ResponseBody
	@RequestMapping(value = "/update")
	public Map<String, Object> update(TSysUser user) {
		tSysUserService.updateTSysUser(user);
		return AjaxUtils.reponseToJson(Constants.Action.UPDATE, true);
	}

	@RequestMapping(value = "/deleteAll")
	@ResponseBody
	public Map<String, Object> delete(@RequestParam(value = "ids", required = true) Integer userId) {
		TSysUserForm form=new TSysUserForm();
		form.setUserId(userId);
		tSysUserService.delTSysUser(MapUtil.toMap(form));
		return AjaxUtils.reponseToJson(Constants.Action.DELETE, true);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@ResponseBody
	@RequestMapping(value = "/getUserTree")
	public List<TSysUser> getUserTree() {
		List list = new ArrayList();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", null);
		map.put("text", "用户树");
		// 子节点
		List<TSysUser> users = tSysUserService.getAllTSysUser(null);
		List childrenList = new ArrayList();
		for (TSysUser user : users) {
			Map<String, Object> childrenMap = new HashMap<String, Object>();
			childrenMap.put("id", user.getUsername());
			childrenMap.put("text", user.getName());
			childrenList.add(childrenMap);
		}
		map.put("children", childrenList);
		list.add(map);
		return list;
	}
}
